package com.eoner.managerlibrary.netsign.version1;

import android.text.TextUtils;

import com.eoner.common.config.Config;
import com.eoner.baselibrary.utils.CookieNewUtil;
import com.eoner.baselib.utils.sp.SPUtils;
import com.eoner.baselibrary.utils.StringsUtils;
import com.eoner.baselibrary.utils.Utils;

import java.io.IOException;
import java.net.URLDecoder;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

import okhttp3.HttpUrl;
import okhttp3.Interceptor;
import okhttp3.MediaType;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
import okio.Buffer;
import okio.BufferedSink;

/**
 * 作者：sean
 * 创建时间：2017/7/13 17:25
 * 功能说明：签名拦截器
 */

public class SignInterceptor implements Interceptor {
    private static final Charset UTF8 = Charset.forName("UTF-8");

    @Override
    public Response intercept(Chain chain) throws IOException {
        String cookie = SPUtils.getInstance().getString(Config.SESSION_ID);
        String buff = "";
        String md5 = "";
        String params = "";
        long timestamp = System.currentTimeMillis()/1000;
        Request request = chain.request();

        RequestBody requestBody = request.body();

        if(requestBody == null){
            requestBody = new RequestBody() {
                @Override
                public MediaType contentType() {
                    return null;
                }

                @Override
                public void writeTo(BufferedSink sink) throws IOException {

                }
            };
        }

        boolean flag = false;
        String host = request.url().url().getHost();
        flag = host.startsWith("api") | host.startsWith("rapi") | host.startsWith("rsapi") | host.startsWith("sapi") | host.startsWith("capi");
        if(flag){

            Buffer buffer = new Buffer();
            requestBody.writeTo(buffer);

            Charset charset = UTF8;
            MediaType contentType = requestBody.contentType();
            if (contentType != null) {
                charset = contentType.charset(UTF8);
            }

            if(contentType!=null&&"multipart".equals(contentType.type())){//排除图片上传的接口
                return chain.proceed(request);
            }


            params = buffer.readString(charset);



            if (!params.contains("timestamp=")) {
                if (TextUtils.isEmpty(params)) {
                    params += ("timestamp=" + Utils.getTimeStamp());
                } else {
                    if (!params.contains("timestamp")) {
                        params += ("&timestamp=" + Utils.getTimeStamp());
                    }
                }
            }
            params += ("&device=" + Utils.getDevicedId());
            params += ("&platform=" + "android");
            params += ("&os=" + android.os.Build.VERSION.RELEASE);
            params += ("&timestamp=" + timestamp);
            params += ("&device_token=" + Config.DEVICE_TOKEN);
            params += ("&device_id=" + Config.DEVICE_ID);
            params += ("&version=" + CookieNewUtil.getVersionName(Utils.getContext()));

            if("get".equalsIgnoreCase(request.method())){
                HttpUrl url = request.url();
                Set<String> paramKeys = url.queryParameterNames();
                for (String key : paramKeys) {
                    String value = url.queryParameter(key);
                    params += ("&" + key + "=" + value);
                }
            }
            String[] pairs = params.split("&");
            Map<String,String> map = new HashMap<>();
            for (String pair:pairs){
                String[] values = pair.split("=");
                //!TextUtils.isEmpty(values[1])
                if(values.length == 2&&!values[0].contains("%5B")&&!values[0].contains("%5D")&&!values[0].contains("[")&&!values[0].contains("]")){
                    map.put(values[0],values[1]);
                }
            }

//            map.put("timestamp",Utils.getTimeStamp()+"");

            List<Map.Entry<String, String>> infoIds = new ArrayList<Map.Entry<String, String>>(map.entrySet());
            // 对所有传入参数按照字段名的 ASCII 码从小到大排序（字典序）
            Collections.sort(infoIds, new Comparator<Map.Entry<String, String>>() {
                @Override
                public int compare(Map.Entry<String, String> o1, Map.Entry<String, String> o2){
                    return (o1.getKey()).toString().compareTo(o2.getKey());
                }
            });
            // 构造URL 键值对的格式
            StringBuilder buf = new StringBuilder();


            for (Map.Entry<String, String> item : infoIds)
            {
//                if(request.url().toString().contains(""))
                if (!TextUtils.isEmpty(item.getKey())) {
                    String key = item.getKey();
                    String val = item.getValue();
//                    Log.i("TAG", "intercept: "+request.url()+"::"+request.method()+"::"+request.body());
                    if(contentType!=null&&"multipart".equals(contentType.type())){
                        continue;
                    }
//                    String urlStr = URLDecoder.decode(val, "UTF-8");
                    buf.append(key + "=" + URLDecoder.decode(val, "UTF-8"));
//                    if("acount".equals(key)||"acount_name".equals(key)){
//                    }else {
//                        buf.append(key + "=" + val);
//                    }
                    buf.append("&");
                }

            }
            buff = buf.toString();
            if (!buff.isEmpty()) {
                buff = buff.substring(0, buff.length() - 1);
            }
//            Log.i("params", params+"intercept: "+buff);
            md5 = StringsUtils.parseStrToMd5U32("87aQr3HQgtTb6EB5zXeW9D7yKwjEfpZR" + buff + "87aQr3HQgtTb6EB5zXeW9D7yKwjEfpZR");
        }

        HttpUrl.Builder authorizedUrlBuilder = request.url()
                .newBuilder()
                .scheme(request.url().scheme())
                .host(request.url().host())
                .addQueryParameter("sign", md5)
                .addQueryParameter("device", Utils.getDevicedId())
                .addQueryParameter("platform", "android")
                .addQueryParameter("os", android.os.Build.VERSION.RELEASE)
                .addQueryParameter("timestamp", "" + timestamp)
                .addQueryParameter("device_token",Config.DEVICE_TOKEN)
                .addQueryParameter("device_id",Config.DEVICE_ID)
                .addQueryParameter("version", CookieNewUtil.getVersionName(Utils.getContext()));

        // 新的请求
//        Request newRequest = request.newBuilder()
//                .method(request.method(), request.body())
//                .url(authorizedUrlBuilder.build())
//                .build();


        Response response;
        if (!TextUtils.isEmpty(md5)) {
            Request.Builder builder = request.newBuilder();
            builder.url(authorizedUrlBuilder.build());
            builder .method(request.method(), request.body());
            RequestBody body = RequestBody.create(okhttp3.MediaType.parse("application/x-www-form-urlencoded; charset=utf-8"),params+"&sign="+md5);
            if("post".equalsIgnoreCase(request.method())){
                builder.post(body);
            }else{
                //builder.get().put(body);
            }
            response = chain.proceed(builder.build());
        }else{
            response = chain.proceed(request);
        }
        return response;
    }
}
